package com.iweb.controller;

import cn.hutool.crypto.SecureUtil;
import com.iweb.constant.UrlRequest;
import com.iweb.pojo.User;
import com.iweb.result.Result;
import com.iweb.service.UserService;
import com.iweb.utils.JsonWriter;
import com.iweb.utils.UrlUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebServlet(value = "/user/*", loadOnStartup = 0)
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 解析url    /user/login    /user/reg
        String action = UrlUtil.url(req.getRequestURI(), UrlRequest.USER_PARENT_URL);
        log.info("用户请求{}", action);
        if ("/reg".equals(action)) handlerReg(req, resp);
        if ("/login".equals(action)) handlerLogin(req, resp);
        if ("/findUserByPhone".equals(action)) handlerFindUserByPhone(req, resp);
        // http://localhost:8090/user/info
        if ("/info".equals(action)) handlerUserInfo(req, resp);
        if ("/email".equals(action)) handlerEmail(req, resp);
        if ("/password".equals(action)) handlerPassword(req, resp);
        if ("/logout".equals(action)) handlerLogout(req, resp);

        // 个人信息跳转
        if ("/toInfo".equals(action)) {
            // 重定向
            resp.sendRedirect("/user/info");
        }
        // 绑定邮箱页面跳转
        if ("/toEmail".equals(action)) {
            // 返回一个message告诉视图我需要显示的邮箱的页面
            req.setAttribute("message", "email");
            req.getRequestDispatcher("/views/user/info/userInfo.jsp").forward(req, resp);
        }
        if ("/toPassword".equals(action)) {
            req.setAttribute("message", "pwd");
            req.getRequestDispatcher("/views/user/info/userInfo.jsp").forward(req, resp);
        }
    }

    private void handlerLogout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 清空session
        req.getSession().invalidate();
        // 返回首页面
        req.getRequestDispatcher("/").forward(req, resp);
    }

    private void handlerPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从session获取当前用户
        HttpSession session = req.getSession();
        Object result = session.getAttribute("user");
//        // 如果用户不存在则返回 login.jsp
//        if (result == null) {
//            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
//            return;
//        }
        // 获取密码并加密
        String password = SecureUtil.md5(req.getParameter("password"));
        // 从session获取用户id
        String userId = ((User) result).getId();

        UserService userService = new UserService();
        userService.updatePassword(userId, password);

        // 获取修改后的userInfo
        User userInfo = userService.findUserInfo(userId);
        req.setAttribute("userInfo", userInfo);

        req.getRequestDispatcher("/views/user/info/userInfo.jsp").forward(req, resp);
    }

    private void handlerEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从session获取当前用户
        HttpSession session = req.getSession();
        Object result = session.getAttribute("user");
//        // 如果用户不存在则返回 login.jsp
//        if (result == null) {
//            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
//            return;
//        }

        // 获取邮箱
        String email = req.getParameter("email");
        // 从session获取用户id
        String userId = ((User) result).getId();
        // 调用service接口
        UserService userService = new UserService();
        User user = userService.updateEmail(userId, email);
        req.setAttribute("userInfo", user);
        req.getRequestDispatcher("/views/user/info/userInfo.jsp").forward(req, resp);
    }

    // 请求用户信息的处理
    private void handlerUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从session获取当前用户
        HttpSession session = req.getSession();
        Object result = session.getAttribute("user");
        // 如果用户不存在则返回 login.jsp
//        if (result == null) {
//            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
//            return;
//        }
        // 如果用户存在 则根据session的id查询用户基本信息
        String userId = ((User) result).getId();
        UserService userService = new UserService();
        User userInfo = userService.findUserInfo(userId);
        // 数据封装到 request 种返回视图 userInfo.jsp
        req.setAttribute("userInfo", userInfo);
        req.getRequestDispatcher("/views/user/info/userInfo.jsp").forward(req, resp);

    }

    // 根据手机号码查询用户
    private void handlerFindUserByPhone(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取手机号
        String phone = req.getParameter("phone");
        // 调用service接口的 findUserByPhone 方法
        UserService userService = new UserService();
        User user = userService.findUserByPhone(phone);
//        if (user == null) {
//            // 如果没有注册 则返回 false
//            JsonWriter.writer(resp, new Result(2000, "ok", true, false));
//        } else {
//            // 否则返回true : json
//            JsonWriter.writer(resp, new Result(2000, "ok", true, true));
//        }
        JsonWriter.writer(resp, new Result(2000, "ok", true, user != null));
    }

    // 处理登录
    private void handlerLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String password = SecureUtil.md5(req.getParameter("password"));
        User user = new User();
        user.setPhone(phone);
        user.setEmail(email);
        user.setPassword(password);

        // 调用service 的 findUserToLogin
        UserService userService = new UserService();
        User userData = userService.findUserToLogin(user);

        // 如果用户不存在 则返回信息
        if (userData == null) {
            req.setAttribute("message", "用户未注册");
            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
            return;
        }
        // 判断密码，如果密码错误则返回信息
        if (!userData.getPassword().equals(password)) {
            req.setAttribute("message", "密码错误");
            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
            return;
        }

        // 将User保存到session中,返回正确信息
        HttpSession session = req.getSession();
        session.setAttribute("user", userData);
        req.getRequestDispatcher("/views/index/index.jsp").forward(req, resp);
    }

    // 处理注册
    private void handlerReg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数，封装user对象
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        User user = new User();
        user.setPhone(phone);
        // 加密
        user.setPassword(SecureUtil.md5(password));
        try {
            // 调用service接口
            UserService userService = new UserService();
            userService.saveUser(user);
            // 成功：返回登录页面
            req.getRequestDispatcher("/views/user/login/login.jsp").forward(req, resp);
        } catch (Exception e) {
            // 失败：返回注册页面，提示用户失败的信息
            log.info(e.getMessage());
            req.setAttribute("message", e.getMessage());
            req.getRequestDispatcher("/views/user/reg/reg.jsp").forward(req, resp);
        }
    }
}
